package sdk.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Dossier;
import sdk.service.DossierManagerService;
import util.Page;

public class GetDossierServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int pageNo = 1;
		int pageSize = 2;
		Page<Dossier> page = null;
		String keycode = "";

		if (null != request.getParameter("searchtype")) {
			request.getSession().setAttribute("searchtype",
					request.getParameter("searchtype"));
		}
		if (null != request.getParameter("keycode")) {
			request.getSession().setAttribute("keycode",
					request.getParameter("keycode"));
			keycode = request.getParameter("keycode");
		} else {
			keycode = (String) request.getSession().getAttribute("keycode");
		}

		try {
			if (request.getParameter("pageNo") != null) {
				pageNo = Integer.parseInt(request.getParameter("pageNo"));
			}
			if (request.getParameter("pageSize") != null) {
				pageSize = Integer.parseInt(request.getParameter("pageSize"));
				request.getSession().setAttribute("pageSize", pageSize);
			}
			if (request.getSession().getAttribute("pageSize") != null) {
				pageSize = (Integer) request.getSession().getAttribute(
						"pageSize");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (keycode != "") {
			if ("dosname".equals(request.getSession()
					.getAttribute("searchtype"))) {
				page = new DossierManagerService().getByDossierName(pageNo,
						pageSize, keycode);
			} else if ("dosno".equals(request.getSession().getAttribute(
					"searchtype"))) {
				try {
					Page<Dossier> p = new Page<Dossier>(1, 1);
					List<Dossier> list = new ArrayList<Dossier>();
					if (null != new DossierManagerService().getByDosNo(keycode)) {
						list.add(new DossierManagerService()
								.getByDosNo(keycode));
						p.setList(list);
						p.setTotalCount(1);
					}
					page = p;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if ("empid".equals(request.getSession().getAttribute(
					"searchtype"))) {
				page = new DossierManagerService().getByEmp(pageNo, pageSize,
						keycode);
			} else {
				page = new DossierManagerService().getAllDossier(pageNo,
						pageSize);
			}
			
		} else {
			page = new DossierManagerService().getAllDossier(pageNo, pageSize);
		}
		// 计算起始记录跟结束记录
		request.setAttribute("page", page);
		request.getRequestDispatcher("/Dossier/Dossier.jsp").forward(request,
				response);
	}

}
